package com.imooc.hadoop.mapreduce.project;
/* @Author Wangjin
 * @Date 2019-01-31
 * @Email wangjin4901@vip.qq.com
 */

import com.kumkee.userAgent.UserAgent;
import com.kumkee.userAgent.UserAgentParser;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 使用MapReduce来完成日志浏览器访问数据的统计
 */
public class LogApp {
    /**
     * Map: 读取输入的文件
     */
    public static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
        LongWritable one = new LongWritable(1);

        private UserAgentParser userAgentParser;

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            userAgentParser  = new UserAgentParser();
        }

        @Override
        protected void cleanup(Context context) throws IOException, InterruptedException {
            userAgentParser = null;
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            // 接收到的每一行的数据:对应我们日志中的每一行数据
            String line = value.toString();
            String source = matcherStr(line, "\"", 2);
            UserAgent agent = userAgentParser.parse(source);
            String browser = agent.getBrowser();
            // 通过上下文把map处理结果输出
            context.write(new Text(browser), one);
        }
    }



    /**
     * 正则匹配指定字符串中指定分隔标识符中间的字符串中的第index个元素
     * @param str 输入的字符串
     * @param operator 分隔符
     * @param index 索引位置
     * @return 匹配到的数据中
     */
    private static String matcherStr(String str, String operator, int index) {
        Pattern pattern = Pattern.compile(operator + ".*?" + operator);
        Matcher matcher = pattern.matcher(str);
        ArrayList<String> list = new ArrayList<>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        return list.get(index);
    }

    /**
     * Reduce: 归并操作
     */
    public static class MyReduce extends Reducer<Text, LongWritable, Text, LongWritable> {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (LongWritable value : values) {
                // 求key出现的次数总和
                sum += value.get();
            }

            // 最终统计结果的输出
            context.write(key, new LongWritable(sum));
        }
    }

    /**
     * 定义Driver: 封装了MapReduce作业的所有信息
     * @param args
     * WC输入输出文件在DFS上的路径
     */

    public static void main(String[] args) throws Exception {
        // 创建Configuration
        Configuration configuration = new Configuration();

        // 准备清理已存在的输出目录
        Path outputPath = new Path(args[1]);
        FileSystem fileSystem = FileSystem.get(configuration);
        if (fileSystem.exists(outputPath)) {
            fileSystem.delete(outputPath, true);
            System.out.println("output file exist, but is has deleted");
        }

        // 创建Job
        Job job = Job.getInstance(configuration, "LogApp");

        // 设置Job的处理类
        job.setJarByClass(LogApp.class);

        // 设置作业处理的输入路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));

        // 设置Map相关的参数
        job.setMapperClass(LogApp.MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        // 设置Reduce相关参数
        job.setReducerClass(LogApp.MyReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        // 设置作业处理的输出路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
